package net.feling.hq711.web;

import java.util.ArrayList;

import net.feling.hq711.Config;
import net.feling.hq711.OrderActivity;
import net.feling.hq711.R;
import net.feling.hq711.TrolleyActivity;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.widget.Toast;

public class Mail {

	private String hostname = "smtp.feling.net";

	private String from = "hq711client@feling.net";
	private String username = "hq711client@feling.net";
	private String passwd = "abcd.1234";

	private String subject = "";
	private String meg = "";
	ProgressDialog progressdialog;
	private String to = "hq711@feling.net";

	private Activity activity;
	private Boolean isorder;// 是订单就显示正在提交订单的进度对话框

	public Mail(Activity activity, String subject, String meg) {
		this.activity = activity;
		this.meg = meg;
		this.subject = subject;
		progressdialog = new ProgressDialog(activity);
	}

	public void send_err() {
		isorder = false;
		new MailTask().execute();
	}

	public void set_order() {
		isorder = true;
		new MailTask().execute();
	}

	private Boolean send() {
		HtmlEmail email = new HtmlEmail();
		email.setHostName(hostname);
		try {
			email.setCharset("utf8");
			email.addTo(to);
			email.setFrom(from);
			email.setAuthentication(username, passwd);
			email.setSubject(subject);
			email.setMsg(meg);
			email.send();
			return true;
		} catch (EmailException e) {
			e.printStackTrace();
			return false;
		}
	}

	private class MailTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (isorder) {
				progressdialog.setMessage(activity.getResources().getString(
						R.string.setting_order));
				progressdialog.setCancelable(false);
				progressdialog.show();
			}
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return send();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (isorder) {
				progressdialog.dismiss();
				if (result == true) {
					Toast.makeText(activity, R.string.set_order_ok,
							Toast.LENGTH_SHORT).show();
					
					for (int i = 0; i < Config.goods_in_trolley.size(); i++) {
						if (Config.goods_in_trolley.get(i).getInt(
								"number") != 0) {
							Config.goods_in_trolley.remove(i);
							i--;
						}
					}
					SharedPreferences preferences = activity.getSharedPreferences("trolley", 0);
					Editor editor = preferences.edit();
					editor.putString("trolley", Config.toXML(Config.goods_in_trolley));
					editor.commit();
					activity.finish();
				} else {
					Toast.makeText(activity, R.string.set_order_fail,
							Toast.LENGTH_SHORT).show();
				}
			}
		}

	}

}
